﻿using com.iot.core.boot;
using com.iot.core.exception;
using com.iot.core.infrastructure;
using System.Diagnostics;
using System.ServiceProcess;

namespace com.iot.ht.Controllers.htsoft.service
{
    public class AppStartSvr : AppStart
    {
        private ServiceController serviceController1 { get; set; } = new ServiceController(); 
        public override async Task<MyApiResult> Start()
        {
            var r = new MyApiResult();
            try
            {
                serviceController1.ServiceName = HtSoftApp.StartInfo;
                serviceController1.MachineName = ".";

                if (serviceController1.Status != ServiceControllerStatus.Running
                    && serviceController1.Status != ServiceControllerStatus.StartPending
                     
                    )
                {
                    serviceController1.Start();
                     
                } 
            }
            catch (Exception ex)
            {
                r.Code = 1;
                r.Msg = MyExceptionUtil.GetExMsg(ex);
            }
            return r;
        }

        public override async Task<MyApiResult> Stop()
        {
            var r = new MyApiResult();
            try
            {
                if (serviceController1 == null)
                {
                    return r;
                } 
                serviceController1 = null;
            }
            catch (Exception ex)
            {
                r.Code = 1;
                r.Msg = MyExceptionUtil.GetExMsg(ex);
            }
            return r;
        }

        public override async Task<MyApiResult> StopEx()
        {
            var r = new MyApiResult();
            try
            {
                if (serviceController1 == null)
                {
                    serviceController1.Stop();
                    return r;
                }
                serviceController1 = null;
            }
            catch (Exception ex)
            {
                r.Code = 1;
                r.Msg = MyExceptionUtil.GetExMsg(ex);
            }
            return r;
        }


        public override async Task<MyApiResult> Check()
        {
            var r = new MyApiResult();
            try
            {
                serviceController1.Refresh();
                if (serviceController1.Status != ServiceControllerStatus.Running
                     && serviceController1.Status != ServiceControllerStatus.StartPending

                     )
                {
                   // serviceController1.Start();
                    r.Code = 2;//重启
                }

                return r;
            }
            catch (Exception ex)
            {
                r.Code = 1;
                r.Msg = MyExceptionUtil.GetExMsg(ex);
            }
            return r;
        }

         
    }
}
